package com.rest.demo.filter;

import com.rest.demo.config.properties.CrosProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author Administrator
 * @decription 跨域过滤器
 * @Date 2017-11-10 15:37
 */
public class CrosFilter extends OncePerRequestFilter {

    @Autowired
    private CrosProperties crosProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String allowOrigin = crosProperties.getAllowOrigin();
        String allowMethods = crosProperties.getAllowMethods();
        String allowCredentials = crosProperties.getAllowCredentials();
        String allowHeaders = crosProperties.getAllowHeaders();
        String exposeHeaders = crosProperties.getExposeHeaders();

        if(StringUtils.isNotEmpty(allowOrigin)) {
            List<String> allowOriginList = Arrays.asList(allowOrigin.split(","));
            if(!allowOriginList.isEmpty()) {
                String currentOrigin = httpServletRequest.getHeader("Origin");
                if(allowOriginList.contains(currentOrigin)) {
                    httpServletResponse.addHeader("Access-Control-Allow-Origin",currentOrigin);
                }
            }
        }

        if(StringUtils.isNotEmpty(allowMethods)) {
            httpServletResponse.addHeader("Access-Control-Allow-Methods",allowMethods);
        }

        if(StringUtils.isNotEmpty(allowCredentials)) {
            httpServletResponse.addHeader("Access-Control-Allow-Credentials",allowCredentials);
        }

        if (StringUtils.isNotEmpty(allowHeaders)) {
            httpServletResponse.setHeader("Access-Control-Allow-Headers", allowHeaders);
        }

        if (StringUtils.isNotEmpty(exposeHeaders)) {
            httpServletResponse.setHeader("Access-Control-Expose-Headers", exposeHeaders);
        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
